package com.polylink.sys.control;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.polylink.base.Page;
import com.polylink.sys.bean.Model;
import com.polylink.sys.service.IModelService;

/**
 *@author xiliang.xiao
 *@date 2015年3月23日 上午9:01:16
 *
 **/
@Controller
@RequestMapping("/model")
public class ModelControl {
	@Autowired
	private IModelService modelService;
	
	@RequiresPermissions("/model")
	@RequestMapping(method=RequestMethod.GET)
	public String index(){
		return "sys/model";
	}

	@RequiresPermissions("/model/save")
	@ResponseBody
	@RequestMapping("save")
	public String add(Model model){
		Map<String,Object> json = new HashMap<String,Object>();
		try{
			boolean b = modelService.save(model);
			if(b){
				json.put("success", true);
			}else{
				json.put("success", false);
				json.put("code", "1");
			}
		}catch(Exception e){
			e.printStackTrace();
			json.put("success", false);
			json.put("code", "-1");
		}
		return JSONObject.fromObject(json).toString();
	}
	
	@RequiresPermissions("/model")
	@ResponseBody
	@RequestMapping("select")
	public String select(){
		List<Model> mList = modelService.select();
		return JSONArray.fromObject(mList).toString();
	}
	
	@RequiresPermissions("/model")
	@ResponseBody
	@RequestMapping("list")
	public String list(
			@RequestParam(value="id",required=false)String id,
			@RequestParam(value="name",required=false)String name,
			@RequestParam(value="remark",required=false)String remark){
		Page p = new Page();
		Map<String,Object> query = new HashMap<String, Object>();
		if(StringUtils.isNotBlank(id)){
			query.put("id", id);
		}
		if(StringUtils.isNotBlank(name)){
			query.put("name", name);
		}
		if(StringUtils.isNotBlank(remark)){
			query.put("remark", remark);
		}
		p.setQuery(query);
		modelService.list(p);
		return JSONObject.fromObject(p).toString();
	}
	
	@RequiresPermissions("/model/delete")
	@ResponseBody
	@RequestMapping("delete")
	public String delete(
			@RequestParam(value="id")String id){
		Map<String,Object> json = new HashMap<String,Object>();
		try{
			boolean b = modelService.delete(id);
			if(b){
				json.put("success", true);
			}else{
				json.put("success", false);
				json.put("code", "1");
			}
		}catch(Exception e){
			e.printStackTrace();
			json.put("success", false);
			json.put("code", "-1");
		}
		return JSONObject.fromObject(json).toString();
	}
}
